package com.chatdating.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chatdating.entity.OrderInfo;
import com.chatdating.entity.PaymentRecord;
import com.chatdating.mapper.OrderInfoMapper;
import com.chatdating.mapper.PaymentRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@Service
public class OrderService extends ServiceImpl<OrderInfoMapper, OrderInfo> {

    private final PaymentRecordMapper paymentRecordMapper;

    public OrderService(PaymentRecordMapper paymentRecordMapper) {
        this.paymentRecordMapper = paymentRecordMapper;
    }

    /**
     * 创建新订单
     */
    @Transactional
    public OrderInfo createOrder(Long userId, String subject, BigDecimal amount) {
        OrderInfo order = new OrderInfo();
        order.setOrderNo(generateOrderNo());
        order.setUserId(userId);
        order.setSubject(subject);
        order.setTotalAmount(amount);
        order.setStatus(0); // 待支付

        save(order);
        return order;
    }

    /**
     * 处理支付回调
     */
    @Transactional
    public boolean processPayment(String outTradeNo, String totalAmount,
                                  Map<String, String> params) {
        // 1. 查询订单
        OrderInfo order = getOrderByNo(outTradeNo);
        if (order == null) {
            log.error("订单不存在: {}", outTradeNo);
            return false;
        }

        // 2. 验证订单状态
        if (order.getStatus() != 0) { // 非待支付状态
            log.warn("订单状态异常, 当前状态: {}, 订单号: {}", order.getStatus(), outTradeNo);
            return false;
        }

        // 3. 验证订单金额
        BigDecimal paymentAmount = new BigDecimal(totalAmount);
        if (order.getTotalAmount().compareTo(paymentAmount) != 0) {
            log.error("订单金额不匹配, 订单金额: {}, 支付金额: {}, 订单号: {}",
                    order.getTotalAmount(), paymentAmount, outTradeNo);
            return false;
        }

        // 4. 获取支付宝交易号
        String tradeNo = params.get("trade_no");

        // 5. 更新订单状态
        int updateCount = baseMapper.updateOrderStatus(
                outTradeNo,
                1, // 已支付
                LocalDateTime.now(),
                tradeNo
        );

        if (updateCount <= 0) {
            log.error("更新订单状态失败, 订单号: {}", outTradeNo);
            return false;
        }

        // 6. 保存支付记录
        savePaymentRecord(order, params, tradeNo, paymentAmount);

        log.info("订单支付成功, 订单号: {}, 支付宝交易号: {}", outTradeNo, tradeNo);
        return true;
    }

    /**
     * 保存支付记录
     */
    private void savePaymentRecord(OrderInfo order, Map<String, String> params,
                                   String transactionId, BigDecimal paymentAmount) {
        PaymentRecord record = new PaymentRecord();
        record.setOrderNo(order.getOrderNo());
        record.setTransactionId(transactionId);
        record.setPaymentAmount(paymentAmount);
        record.setPaymentStatus(1); // 支付成功
        record.setPaymentMethod(1); // 支付宝
        record.setPaymentTime(LocalDateTime.now());
        record.setNotifyData(params);

        paymentRecordMapper.insert(record);
    }

    /**
     * 根据订单号查询订单
     */
    public OrderInfo getOrderByNo(String orderNo) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        return getOne(queryWrapper);
    }

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        return "O" + System.currentTimeMillis() + (int)(Math.random() * 1000);
    }
}
